package com.ruoyi.distributor.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.map.MapUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecureUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.distributionConfig.domain.DistributionConfig;
import com.ruoyi.distributionConfig.service.IDistributionConfigService;
import com.ruoyi.distributionGrade.domain.DistributionGrade;
import com.ruoyi.distributionGrade.service.IDistributionGradeService;
import com.ruoyi.distributor.domain.DistributorDetailVo;
import com.ruoyi.distributor.domain.DistributorFanVo;
import com.ruoyi.relation.domain.DistributionRelation;
import com.ruoyi.relation.service.IDistributionRelationService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wallet.domain.DistributionWallet;
import com.ruoyi.wallet.service.IDistributionWalletService;
import com.ruoyi.withdraw.domain.DistributionWithdraw;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.distributor.domain.DistributionUser;
import com.ruoyi.distributor.service.IDistributionUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 分销用户信息Controller
 * 
 * @author ruoyi
 * @date 2025-10-11
 */
@RestController
@RequestMapping("/ruoyi/distributor")
public class DistributionUserController extends BaseController
{
    @Autowired
    private IDistributionUserService distributionUserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDistributionGradeService distributionGradeService;

    @Autowired
    private IDistributionConfigService distributionConfigService;

    @Autowired
    private IDistributionRelationService distributionRelationService;

    @Autowired
    private IDistributionWalletService walletService;

    /**
     * 获取当前分销员的粉丝列表
     */
    @GetMapping("/fans")
    public TableDataInfo getFansList() {
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();

        // 获取当前用户的分销员信息
        DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
        if (distributor == null) {
            return getDataTable(new ArrayList<>());
        }

        // 查询该分销员的下级关系列表
        List<DistributionRelation> relationList = distributionRelationService.selectSubordinatesByDistributorId(distributor.getDistributorId());

        // 获取下级分销员的详细信息
        List<DistributorFanVo> fansList = new ArrayList<>();
        for (DistributionRelation relation : relationList) {
            DistributionUser fan = distributionUserService.selectDistributionUserByDistributorId(relation.getSubordinateId());
            if (fan != null) {
                DistributorFanVo fanVo = new DistributorFanVo();
                fanVo.setDistributorId(fan.getDistributorId());
                fanVo.setRealName(fan.getRealName());
                fanVo.setMobile(fan.getMobile());
                fanVo.setBindTime(fan.getBindTime());
                fanVo.setTeamCount(fan.getTeamCount());
                fanVo.setDirectCount(fan.getDirectCount());
                fanVo.setRelationLevel(relation.getRelationLevel());
                fansList.add(fanVo);
            }
        }

        return getDataTable(fansList);
    }



    /**
     * 根据分销员编号查询分销员信息
     */
    @GetMapping("/getByDistributorCode/{distributorCode}")
    public AjaxResult getDistributorByCode(@PathVariable("distributorCode") String distributorCode)
    {
        DistributionUser distributor = distributionUserService.selectDistributionUserByDistributorCode(distributorCode);
        if (distributor != null) {
            return AjaxResult.success(distributor);
        } else {
            return AjaxResult.error("未找到对应的分销员信息");
        }
    }


    /**
     * 小程序端用户扫码绑定分销关系
     * 用户扫码自动绑定分销关系（无感绑定）
     * 当非分销员用户扫码分销员专属二维码时，自动成为该分销员的关注者
     */
    @PostMapping("/autoBindRelation")
    public AjaxResult autoBindRelation(@RequestBody Map<String, String> params) {
        try {
            String inviteCode = params.get("inviteCode");
            if (StringUtils.isEmpty(inviteCode)) {
                return AjaxResult.error("邀请码不能为空");
            }

            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();
            Long userId = loginUser.getUserId();

            // 统一在Service层处理自动绑定逻辑
            int result = distributionUserService.autoBindRelation(inviteCode, userId);

            if (result > 0) {
                return AjaxResult.success("关注成功");
            } else {
                return AjaxResult.error("关注失败");
            }
        } catch (ServiceException e) {
            logger.error("自动绑定分销关系异常", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("自动绑定分销关系异常", e);
            return AjaxResult.error("关注失败：" + e.getMessage());
        }
    }


    /**
     * 获取分销申请协议
     */
    @GetMapping("/applyProtocol")
    public AjaxResult getApplyProtocol() {
        DistributionConfig config = distributionConfigService.selectDistributionConfigByConfigId(1L);
        if (config != null) {
            return AjaxResult.success(config.getApplyProtocol());
        }
        return AjaxResult.success();
    }

    /**
     * 审核分销员申请
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:audit')")
    @PutMapping("/audit")
    public AjaxResult auditDistributor(@RequestBody DistributionUser distributionUser) {
        try {
            // 检查参数
            if (distributionUser.getDistributorId() == null ||
                StringUtils.isEmpty(distributionUser.getAuthStatus())) {
                return AjaxResult.error("参数不完整");
            }

            // 获取原记录
            DistributionUser oldUser = distributionUserService.selectDistributionUserByDistributorId(
                distributionUser.getDistributorId());
            if (oldUser == null) {
                return AjaxResult.error("分销员信息不存在");
            }

            // 更新状态
            oldUser.setAuthStatus(distributionUser.getAuthStatus());
            if ("1".equals(distributionUser.getAuthStatus())) {
                // 审核通过，设置绑定时间
                oldUser.setBindTime(new Date());
            }
            oldUser.setRemark(distributionUser.getRemark());

            int result = distributionUserService.updateDistributionUser(oldUser);

            // 记录操作日志
            String action = "1".equals(distributionUser.getAuthStatus()) ? "审核通过" : "审核拒绝";
            distributionUserService.recordDistributionLog(oldUser.getDistributorId(), "5", action,
                "平台审核分销员申请", distributionUser.getRemark(), "");

            return toAjax(result);
        } catch (Exception e) {
            return AjaxResult.error("审核失败");
        }
    }


    /**
     * 获取所有分销员基础信息（仅ID和姓名）
     */
    @GetMapping("/basicList")
    public AjaxResult listDistributorsBasic() {
        List<DistributionUser.DistributorBasicInfo> list = distributionUserService.selectDistributorBasicList();
        return AjaxResult.success(list);
    }

    /**
     * web端 管理员审核分销员申请的接口
     * 审核分销员，修改分销用户信息
     * 重构后：Controller层只负责参数校验和调用Service层
     */
    @PutMapping("/updateDistributorApply")
    public AjaxResult updateDistributorApply(@RequestBody DistributionUser distributionUser)
    {
        try {
            // 参数校验
            if (distributionUser.getDistributorId() == null ||
                    StringUtils.isEmpty(distributionUser.getAuthStatus())) {
                return AjaxResult.error("参数不完整");
            }

            // 调用Service层进行审核处理
            int result = distributionUserService.auditDistributorApply(
                    distributionUser.getDistributorId(),
                    distributionUser.getAuthStatus(),
                    distributionUser.getRemark());

            return toAjax(result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("审核分销员申请异常", e);
            return AjaxResult.error("审核失败");
        }
    }

    /**
     * 获取分销员列表时，将待审核状态为'0'（待审核）的优先级设为最高，排在最前面
     * 获取分销员汇总列表
     */
    @GetMapping("/selectDistributorSummaryList")
    public TableDataInfo selectDistributorSummaryList(DistributionUser distributor) {
        startPage();
        List<DistributionUser> list = distributionUserService.selectDistributorSummaryList(distributor);
        return getDataTable(list);
    }

    /**
     * 获取待审核分销员数量
     */
    @GetMapping("/pendingCount")
    public AjaxResult getPendingDistributorCount() {
        int count = distributionUserService.selectPendingDistributorCount();
        return AjaxResult.success(count);
    }

    /**
     * 查询分销员表中是否存在某个 userId
     */
    @GetMapping("/selectDistributorWhereUserId")
    public AjaxResult selectDistributorWhereUserId()
    {
        // 获取当前用户ID
        Long userId = getUserId();
        Long distributorUserId = distributionUserService.selectDistributorWhereUserId(userId);
        if (distributorUserId == 0) {
            return success(false);
        } else {
            return success(true);
        }
    }

    /**
     * 获取当前登录用户的分销员的个人信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:distributor_profile')") // 权限控制
    @GetMapping("/distributor_profile")
    public AjaxResult distributorProfile() {
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();

        // 通过用户ID查询关联的分销员信息（需实现关联逻辑）
//        DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
        DistributorDetailVo detailVo = distributionUserService.getDistributorDetail(loginUser.getUserId());

        if (detailVo == null) {
            return AjaxResult.error("分销员信息不存在");
        }
        return AjaxResult.success(detailVo);
    }

    /**
     * 获取当前用户分销员状态
     */
    @GetMapping("/getCurrent")
    public AjaxResult getCurrentDistributor() {
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();

        DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
        if (distributor == null) {
            return AjaxResult.error("分销员信息不存在");
        }

        // 如果分销员有等级ID，则获取等级名称
        if (distributor.getGradeId() != null) {
            DistributionGrade grade = distributionGradeService.selectDistributionGradeByGradeId(distributor.getGradeId());
            if (grade != null) {
                distributor.setGradeName(grade.getGradeName());
            }
        }
        return AjaxResult.success(distributor);
    }

    /**
     * web端 新用户用于申请分销员身份的接口
     * 提交分销员申请
     */
    @PostMapping("/applicationDistributor")
    public AjaxResult applicationDistributor(@RequestBody DistributionUser distributionUser) {
        try {
            Long userId = SecurityUtils.getUserId();
            distributionUser.setUserId(userId);

            // 统一在Service层处理申请逻辑
            int result = distributionUserService.applyDistributor(distributionUser);
            return toAjax(result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("分销员申请异常", e);
            return AjaxResult.error("申请失败");
        }
    }


    /**
     * 提交分销员申请
     */
    @PostMapping("/apply")
    public AjaxResult applyDistributor(@RequestBody DistributionUser distributionUser) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(userId);
        if (distributor != null) {
            // 如果已经存在申请，且不是审核未通过状态，则不允许重复申请
            // 认证状态(0待审核 1已通过 2未通过)
            if (!"2".equals(distributor.getAuthStatus())) {
                return AjaxResult.error("您已经提交过分销员申请，请勿重复申请");
            }
            // 如果之前申请未通过，可以重新申请，更新相关信息
            distributor.setAuthStatus("0"); // 重新设置为待审核
            distributor.setRealName(distributionUser.getRealName());
            distributor.setMobile(distributionUser.getMobile());
            distributor.setIdentityCard(distributionUser.getIdentityCard());
            // 保留原有的fatherId，如果新的申请中有设置则更新
            if (distributionUser.getFatherId() != null) {
                distributor.setFatherId(distributionUser.getFatherId());
            }

            distributor.setUpdateTime(new Date());
            distributor.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(distributionUserService.updateDistributionUser(distributor));
        }

        // 当前用户没有关联分销信息申请时，则插入新的申请记录
        distributionUser.setUserId(userId); // 设置申请人ID为当前登录用户ID
        distributionUser.setAuthStatus("0"); // 设置默认状态：审核中
        // 设置默认等级ID（可根据实际情况调整）
        DistributionGrade grade = distributionGradeService.selectDefaultGrade();
        if (distributionUser.getGradeId() == null) {
            distributionUser.setGradeId(grade.getGradeId()); // 默认等级ID
        }
        // 设置默认上级ID为0（如果没有推荐人）
        if (distributionUser.getFatherId() == null) {
            distributionUser.setFatherId(0L);
        }

        // 构建返回值
        int result;
        // 新增申请记录
        result = distributionUserService.insertDistributionUser(distributionUser);
        return toAjax(result);
    }


    /**
     * 查询分销用户信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:list')")
    @GetMapping("/list")
    public TableDataInfo list(DistributionUser distributionUser)
    {
        startPage();
        List<DistributionUser> list = distributionUserService.selectDistributionUserList(distributionUser);
        return getDataTable(list);
    }

    /**
     * 导出分销用户信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:export')")
    @Log(title = "分销用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DistributionUser distributionUser)
    {
        List<DistributionUser> list = distributionUserService.selectDistributionUserList(distributionUser);
        ExcelUtil<DistributionUser> util = new ExcelUtil<DistributionUser>(DistributionUser.class);
        util.exportExcel(response, list, "分销用户信息数据");
    }

    /**
     * 获取分销用户信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:query')")
    @GetMapping(value = "/{distributorId}")
    public AjaxResult getInfo(@PathVariable("distributorId") Long distributorId)
    {
        return success(distributionUserService.selectDistributionUserByDistributorId(distributorId));
    }

    /**
     * 获取分销员详情信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:info')")
    @GetMapping("/info")
    public AjaxResult  getDistributorInfo() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 获取分销员详情
        DistributorDetailVo detailVo = distributionUserService.getDistributorDetail(userId);

        return success(detailVo);
    }

    /**
     * 新增分销用户信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:add')")
    @Log(title = "分销用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DistributionUser distributionUser)
    {
        return toAjax(distributionUserService.insertDistributionUser(distributionUser));
    }

    /**
     * 分销员脱离上级关系
     */
    @PreAuthorize("@ss.hasPermi('distributor:distributor:edit')")
    @Log(title = "分销员脱离上级关系", businessType = BusinessType.UPDATE)
    @PutMapping("/unbindSuperior")
    public AjaxResult unbindSuperior(@RequestBody Map<String, Object> params)
    {
        Long distributorId = MapUtil.getLong(params, "distributorId");
        String remark = MapUtil.getStr(params, "remark", "分销员主动脱离上级关系");

        if (distributorId == null) {
            return AjaxResult.error("分销员ID不能为空");
        }

        try {
            int result = distributionUserService.unbindSuperiorRelation(distributorId, remark);
            return result > 0 ? AjaxResult.success("脱离上级关系成功") : AjaxResult.error("脱离上级关系失败");
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改分销用户信息
     */
    @PreAuthorize("@ss.hasPermi('distributor:distributor:edit')")
    @Log(title = "分销用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DistributionUser distributionUser)
    {
        return toAjax(distributionUserService.updateDistributionUser(distributionUser));
    }

    /**
     * 删除分销用户信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:distributor:remove')")
    @Log(title = "分销用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{distributorIds}")
    public AjaxResult remove(@PathVariable Long[] distributorIds)
    {
        return toAjax(distributionUserService.deleteDistributionUserByDistributorIds(distributorIds));
    }


    /**
     * 提现申请
     */
    @PostMapping("/withdraw")
    public AjaxResult withdrawCommission(@RequestBody DistributionWithdraw withdraw) {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 检查分销员状态
            if (!"0".equals(distributor.getStatus()) || !"1".equals(distributor.getAuthStatus())) {
                return AjaxResult.error("分销员状态异常，无法提现");
            }

            // 设置分销员ID
            withdraw.setDistributorId(distributor.getDistributorId());

            // 检查提现金额是否大于0
            if (withdraw.getAmount() == null || withdraw.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return AjaxResult.error("提现金额必须大于0");
            }

            // 获取分销配置，检查最小提现金额
            DistributionConfig config = distributionConfigService.selectDistributionConfigByConfigId(1L);
            if (config != null && config.getMinWithdrawAmount() != null) {
                if (withdraw.getAmount().compareTo(config.getMinWithdrawAmount()) < 0) {
                    return AjaxResult.error("提现金额不能低于最低提现金额：" + config.getMinWithdrawAmount());
                }
            }

            // 获取钱包信息
            DistributionWallet wallet = walletService.selectWalletByDistributorId(distributor.getDistributorId());
            if (wallet == null) {
                return AjaxResult.error("未找到钱包信息");
            }

            // 检查余额是否充足
            if (wallet.getAvailableBalance() == null || wallet.getAvailableBalance().compareTo(withdraw.getAmount()) < 0) {
                return AjaxResult.error("可用余额不足");
            }

            // 计算手续费（如果有配置税率）
            BigDecimal fee = BigDecimal.ZERO;
            if (config != null && config.getTaxRate() != null) {
                fee = withdraw.getAmount().multiply(config.getTaxRate()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
            }

            // 计算实际到账金额
            BigDecimal actualAmount = withdraw.getAmount().subtract(fee);

            // 设置提现单号
            withdraw.setWithdrawCode(IdUtils.generateWithdrawCode());

            // 设置金额信息
            withdraw.setFee(fee);
            withdraw.setActualAmount(actualAmount);

            // 设置状态
            withdraw.setStatus("0");
            withdraw.setDelFlag("0");
            withdraw.setAuditStatus("0"); // 待审核

            // 调用提现服务
            // 这里需要在 IDistributionWithdrawService 中添加相关方法
            // withdrawService.insertDistributionWithdraw(withdraw);

            // 记录操作日志
            distributionUserService.recordDistributionLog(
                distributor.getDistributorId(),
                "4",
                "申请提现",
                "用户申请提现",
                "提现金额：" + withdraw.getAmount() + "，手续费：" + fee + "，实际到账：" + actualAmount,
                "");

            return AjaxResult.success("提现申请已提交");
        } catch (Exception e) {
            logger.error("提现申请异常", e);
            return AjaxResult.error("提现申请失败：" + e.getMessage());
        }
    }

    /**
     * 生成分销海报
     */
    @GetMapping("/poster")
    public AjaxResult generatePoster() {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 检查分销员状态
            if (!"0".equals(distributor.getStatus()) || !"1".equals(distributor.getAuthStatus())) {
                return AjaxResult.error("分销员状态异常，无法生成海报");
            }

            // 构建海报信息
            Map<String, Object> posterInfo = new HashMap<>();
            posterInfo.put("distributorCode", distributor.getDistributorCode());

            // 生成小程序二维码的路径
            String qrCodePath = "/pages/mine/distribution/apply?distributorCode=" + distributor.getDistributorCode();
            posterInfo.put("qrCodeUrl", qrCodePath);

            // 生成完整的小程序页面路径
            String pagePath = "pages/mine/distribution/apply";
            posterInfo.put("pagePath", pagePath);
            posterInfo.put("scene", distributor.getDistributorCode());

            return AjaxResult.success(posterInfo);
        } catch (Exception e) {
            logger.error("生成海报异常", e);
            return AjaxResult.error("生成海报失败：" + e.getMessage());
        }
    }


    /**
     * 获取分销员小程序二维码
     */
    @GetMapping("/qrcode")
    public AjaxResult getDistributorQRCode() {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 检查分销员状态
            if (!"0".equals(distributor.getStatus()) || !"1".equals(distributor.getAuthStatus())) {
                return AjaxResult.error("分销员状态异常，无法生成二维码");
            }

            // 生成小程序二维码需要的参数
            Map<String, Object> qrCodeInfo = new HashMap<>();
            qrCodeInfo.put("distributorCode", distributor.getDistributorCode());
            qrCodeInfo.put("scene", distributor.getDistributorCode()); // 小程序扫码后的参数
            qrCodeInfo.put("page", "pages/index/index"); // 小程序页面路径

            // 这里需要调用微信API生成二维码
            // 实际实现需要:
            // 1. 获取微信access_token
            // 2. 调用微信生成二维码接口
            // 3. 返回二维码图片链接或base64数据

            return AjaxResult.success(qrCodeInfo);
        } catch (Exception e) {
            logger.error("生成二维码异常", e);
            return AjaxResult.error("生成二维码失败：" + e.getMessage());
        }
    }



    /**
     * 微信小程序接口 wx.createQRCode
     * 获取当前用户的分销员编码
     */
    @GetMapping("/code")
    public AjaxResult getDistributorCode() {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            return AjaxResult.success(distributor.getDistributorCode());
        } catch (Exception e) {
            logger.error("获取分销员编码异常", e);
            return AjaxResult.error("获取分销员编码失败：" + e.getMessage());
        }
    }


    /**
     * 绑定分销关系
     */
    @PostMapping("/bindRelation")
    public AjaxResult bindDistributionRelation(@RequestBody Map<String, String> params) {
        try {
            String inviteCode = params.get("inviteCode");
            if (StringUtils.isEmpty(inviteCode)) {
                return AjaxResult.error("邀请码不能为空");
            }

            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 检查是否已经有上级
            if (distributor.getFatherId() != null && distributor.getFatherId() > 0) {
                return AjaxResult.error("您已绑定上级，无法重复绑定");
            }

            // 调用绑定关系服务
            int result = distributionUserService.bindInvitationRelation(inviteCode, distributor.getDistributorId());

            if (result > 0) {
                return AjaxResult.success("绑定成功");
            } else {
                return AjaxResult.error("绑定失败");
            }
        } catch (ServiceException e) {
            logger.error("绑定分销关系异常", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("绑定分销关系异常", e);
            return AjaxResult.error("绑定失败：" + e.getMessage());
        }
    }

    /**
     * 手动绑定上级分销员
     */
    @PostMapping("/bindSuperiorDistributor")
    public AjaxResult bindSuperiorDistributor(@RequestBody Map<String, String> params) {
        try {
            String superiorDistributorCode = params.get("superiorDistributorCode");
            String remark = params.get("remark");

            if (StringUtils.isEmpty(superiorDistributorCode)) {
                return AjaxResult.error("上级分销员编码不能为空");
            }

            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 调用手动绑定上级分销员服务
            int result = distributionUserService.bindSuperiorDistributor(
                distributor.getDistributorId(),
                superiorDistributorCode,
                StringUtils.isNotEmpty(remark) ? remark : "手动绑定上级分销员"
            );

            if (result > 0) {
                return AjaxResult.success("绑定上级分销员成功");
            } else {
                return AjaxResult.error("绑定上级分销员失败");
            }
        } catch (ServiceException e) {
            logger.error("手动绑定上级分销员异常", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("手动绑定上级分销员异常", e);
            return AjaxResult.error("绑定失败：" + e.getMessage());
        }
    }


    /**
     * 禁用分销员
     */
    @PreAuthorize("@ss.hasPermi('distributor:distributor:disable')")
    @Log(title = "分销员禁用", businessType = BusinessType.UPDATE)
    @PutMapping("/disable/{distributorId}")
    public AjaxResult disableDistributor(@PathVariable Long distributorId, @RequestBody Map<String, String> params) {
        try {
            String remark = params.getOrDefault("remark", "管理员禁用");
            distributionUserService.disableDistributorAndHandleCommission(distributorId, remark);
            return AjaxResult.success("分销员禁用成功");
        } catch (Exception e) {
            return AjaxResult.error("分销员禁用失败：" + e.getMessage());
        }
    }

    /**
     * 生成分销商品海报
     */
    @PostMapping("/generateProductPoster")
    public AjaxResult generateProductPoster(@RequestBody Map<String, Object> params) {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();

            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());
            if (distributor == null) {
                return AjaxResult.error("您还不是分销员");
            }

            // 检查分销员状态
            if (!"0".equals(distributor.getStatus()) || !"1".equals(distributor.getAuthStatus())) {
                return AjaxResult.error("分销员状态异常，无法生成海报");
            }

            // 获取参数
            Long productId = MapUtil.getLong(params, "productId");
            if (productId == null) {
                return AjaxResult.error("商品ID不能为空");
            }

            // 验证分销员是否有权限推广此商品
            // 这里可以根据业务需求添加具体的验证逻辑

            // 调用服务生成海报
            Map<String, Object> posterInfo = distributionUserService.generateProductPoster(
                distributor.getDistributorId(),
                productId
            );

            return AjaxResult.success(posterInfo);
        } catch (Exception e) {
            logger.error("生成商品海报异常", e);
            return AjaxResult.error("生成海报失败：" + e.getMessage());
        }
    }



}
